import 'dart:convert';
import 'package:base_flutter/base_flutter.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:ls_work/a_yyt/models/pending_selected_group_entity.dart';
import 'package:ls_work/a_yyt/page/pending_selected_group_page.dart';
import 'package:ls_work/a_yyt/page/pending_selected_staff_page.dart';
import 'package:ls_work/mvp/svp_progress.dart';
import 'package:ls_work/net/HttpUtil.dart';
import 'package:ls_work/net/net.dart';
import 'package:ls_work/res/colors.dart';
import 'package:ls_work/res/styles.dart';
import 'package:ls_work/util/toast.dart';

import '../../util/flat_button.dart';



class PendingGroupPage extends StatefulWidget {
  final Function(
    List<List<PendingSelectedGroupEntity>> groupList,
    List<PendingSelectedGroupEntity> staffList,
    int index,
  )? callBack;
  PendingGroupPage({Key? key, this.callBack});
  @override
  _PendingGroupPageState createState() => _PendingGroupPageState();
}

class _PendingGroupPageState extends State<PendingGroupPage>
    with SingleTickerProviderStateMixin, AutomaticKeepAliveClientMixin {
  PageController _pageController = PageController(initialPage: 0);
  TabController? _tabController;

  List<List<PendingSelectedGroupEntity>> sortList = [];
  List<PendingSelectedGroupEntity> orginList = [];
  int currentIndex = 0;
  @override
  bool get wantKeepAlive => true;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      _getAllByCurBranchWithUsers();
    });
    _tabController = new TabController(vsync: this, length: 2);
  }

  @override
  void dispose() {
    _tabController?.dispose();
    _pageController.dispose();
    super.dispose();
  }

  _onPageChange(int index) {
    _tabController?.animateTo(index);
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Scaffold(
      appBar: AppBar(
        title: Text('选择'),
        elevation: 0.5,
        actions: <Widget>[
          FlatsButton(
            onPressed: () {
              if(widget.callBack!=null){
                widget.callBack!(sortList, orginList, currentIndex);
              }
              Navigator.pop(context);
            },
            child: Text(
              '确定',
              style: TextStyle(
                color: Colours.app_main,
                fontSize: 18,
              ),
            ),
          )
        ],
        bottom: TabBar(
          onTap: (index) {
            if (!mounted) {
              return;
            }
            currentIndex = index;
            Toast.show('组和人只能选择一种，按照最后选择为准');
            _pageController.jumpToPage(index);
          },
          isScrollable: false,
          controller: _tabController,
          labelStyle: TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
          indicatorSize: TabBarIndicatorSize.label,
          unselectedLabelColor: Colours.text_gray,
          unselectedLabelStyle: TextStyles.textGray14,
          labelColor: Colours.text_dark,
          indicatorColor: Colours.app_main,
          indicatorPadding: EdgeInsets.only(bottom: 5),
          tabs: <Widget>[
            Tab(
              text: '分配到组',
            ),
            Tab(
              text: '分配到人',
            ),
          ],
        ),
      ),
      body: PageView.builder(
        key: const Key('pageView'),
        itemCount: 5,
        onPageChanged: _onPageChange,
        controller: _pageController,
        itemBuilder: (BuildContext context, int index) {
          switch (index) {
            case 0:
              return PendingSelectedGroupPage(sortList: sortList);
              break;
            case 1:
              return PendingSelectedStaffPage(orginList: orginList);
              break;
            default:
              return Container(
                child: Center(
                  child: Text(
                    '暂无内容',
                    style: TextStyles.textGray14,
                  ),
                ),
              );
          }
        },
      ),
    );
  }

  ///获取分组
  void _getAllByCurBranchWithUsers() {
    SVProgressHUD page = SVProgressHUD(context);
    page.showProgress();
    HttpUtil.instance
        .getDio()
        .post(
          HttpApi.getAllByCurBranchWithUsers,
        )
        .then((r) {
      ///
      page.closeProgress();
      if (r.statusCode == 200) {
        Map<String, dynamic> map = json.decode(r.toString());
        if (map["code"].toString() == "0") {
          print('11111');
          if (map['data'] != null) {
            print('2222');
            PendingSelectedGroupSection model =
                PendingSelectedGroupSection.fromJson(map);
            print('333');
            orginList = model.data??[];
            var newMap = {};
            List<List<PendingSelectedGroupEntity>> sectionList = [];
            for (var i = 0; i < (model.data??[]).length; i++) {
              PendingSelectedGroupEntity info = model.data![i];
              if (newMap[info.serviceTypeName] == null) {
                List<PendingSelectedGroupEntity> tempList = [];
                tempList.add(info);
                sectionList.add(tempList);
                newMap[info.serviceTypeName] = info;
              } else {
                for (var j = 0; j < sectionList.length; j++) {
                  PendingSelectedGroupEntity dj = sectionList[j].first;
                  if (dj.serviceTypeName == info.serviceTypeName) {
                    sectionList[j].add(info);
                    break;
                  }
                }
              }
            }
            sortList.addAll(sectionList);
            // for (List<PendingSelectedGroupEntity> section in sectionList) {
            //   List<PendingSelectedGroupInfo> user1 = [];
            //   for (PendingSelectedGroupEntity item in section) {
            //     user1.addAll(item.user);
            //   }
            // sectionList.first.first.user = user1;
            // sectionList.first.first.name = sectionList.first.first.name;
            // sectionList.first.first.serviceTypeName =
            //     sectionList.first.first.serviceTypeName;
            // sortList.add(sectionList.first.first);
            // }
            // print('🍎 - sortListlength - ${sortList.length}');
            // print('🍎 - orginListListlength - ${orginList.length}');
          } else {
            Toast.show(map["msg"]);
          }
        } else {
          Toast.show(map["msg"]);
        }
      } else {
        Toast.show(r.statusCode.toString());
      }
    }).catchError((e) {
      page.closeProgress();
      print(e.toString());
      Toast.show(getErrorMessage(e));
    });
  }
}
